﻿/* Copyright (c) 2010 Lexalytics Inc.

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

// Needed for Office and Excel integration
using Excel = Microsoft.Office.Interop.Excel;


namespace Lexalytics4Excel.Dialogs
{
    /// <summary>
    /// Dialog allowing user to specify column and value to filter results on
    /// </summary>
    public partial class FilterDialog : Form
    {
        #region Member variables
        private string wsName = "";
        private Excel.Range dataRange;
        private bool bIncludesHeader = false;
        private string strTextColumn = "A";
        private int nTextColumn = 1;
        private SortedList<int, string> lstColumns = new SortedList<int, string>();
        private Database.SqlHelper LocalDB = null;

        /// <summary>
        /// Metadata column label to filter results on
        /// </summary>
        public string FilterColumn = "";

        /// <summary>
        /// Metadata value from selected metadata column to fiulter results on
        /// </summary>
        public string FilterValue = "";
        #endregion // Member variables

        /// <summary>
        /// Constructor for the dialog
        /// </summary>
        /// <param name="CurrentProject">Current data project</param>
        public FilterDialog(DataProject CurrentProject)
        {
            wsName = CurrentProject.UserRangeWorksheet;
            Excel.Worksheet ws = (Excel.Worksheet)Globals.LexalyticsAddIn.Application.Worksheets[wsName];
            dataRange = ws.get_Range(CurrentProject.UserRangeSelection,Type.Missing);
            bIncludesHeader = CurrentProject.UserRangeIncludesHeader;
            strTextColumn = CurrentProject.UserRangeTextColumn;
            LocalDB = CurrentProject.LocalDatabase;
            InitializeComponent();
        }

        #region Event handlers

        /// <summary>
        /// Event handler for form load, initializes user interface based on current data project
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FilterDialog_Load(object sender, EventArgs e)
        {
            try
            {
                // Fill dropdown of filter column names
                string sColHeader = "";

                ColumnDropdown.Items.Clear();

                // Determine number of columns
                int nMinCol = 1;
                int nMaxCol = 1;
                string strRange_R1C1 = dataRange.get_Address(1, Type.Missing, Excel.XlReferenceStyle.xlR1C1, Type.Missing, Type.Missing);
                string[] arrBounds = strRange_R1C1.Split(new char[] { 'R', 'C', ':' }, StringSplitOptions.RemoveEmptyEntries);
                switch (arrBounds.GetLength(0))
                {
                    case 2:
                        nMinCol = Convert.ToInt32(arrBounds[0]);
                        nMaxCol = Convert.ToInt32(arrBounds[1]);
                        break;
                    case 4:
                        nMinCol = Convert.ToInt32(arrBounds[1]);
                        nMaxCol = Convert.ToInt32(arrBounds[3]);
                        break;
                    default:
                        nMaxCol = dataRange.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Column;
                        break;
                }

                // Determine index of text column
                Excel.Worksheet ws = (Excel.Worksheet)Globals.LexalyticsAddIn.Application.Worksheets[wsName];
                Excel.Range _rng = ws.get_Range(String.Format("${0}$1:${0}$1", strTextColumn), Type.Missing);
                strRange_R1C1 = _rng.get_Address(1, 1, Excel.XlReferenceStyle.xlR1C1, Type.Missing, Type.Missing);
                arrBounds = strRange_R1C1.Split(new char[] { 'R', 'C', ':' }, StringSplitOptions.RemoveEmptyEntries);
                nTextColumn = Convert.ToInt32(arrBounds[1]);

                for (int nColIndex = nMinCol; nColIndex <= nMaxCol; nColIndex++)
                {
                    if (nColIndex != Convert.ToInt32(nTextColumn))
                    {
                        if (bIncludesHeader)
                        {
                            Excel.Range rHeader = (Excel.Range)dataRange.Cells[1, nColIndex];
                            if (rHeader.Value2 != null)
                                sColHeader = rHeader.Value2.ToString();
                            else
                                sColHeader = String.Format("Column{0}", nColIndex);
                        }
                        else
                        {
                            Excel.Range rHeader = (Excel.Range)dataRange.Cells[1, nColIndex];
                            sColHeader = String.Format("Column{0}", nColIndex);
                        }
                        lstColumns.Add(nColIndex, sColHeader);
                        ColumnDropdown.Items.Add(lstColumns[nColIndex]);
                    }
                }
                if (ColumnDropdown.Items.Count > 0)
                    ColumnDropdown.SelectedIndex = 0;
            }
            catch (Exception err)
            {
                MessageBox.Show("There was a problem determining the possible filter options.\n" + err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                OKButton.Enabled = false;
            }
        }

        /// <summary>
        /// Event handler for column selector, gets unique values 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ColumnDropdown_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ColumnDropdown.SelectedItem.ToString().Length == 0)
                return;

            ValueDropdown.Items.Clear();

            string sColHeader = ColumnDropdown.SelectedItem.ToString();

            // Fill value dropdown with unique items from database
            try
            {
                List<string> lstUniqueValues = new List<string>();
                if (LocalDB != null)
                {
                    LocalDB.execute(String.Format("SELECT DISTINCT(value) FROM metadata WHERE label='{0}'", LocalDB.makeSafe(sColHeader)));
                    while (LocalDB.nextRow())
                    {
                        object[] oRow = LocalDB.getRow();
                        string strValue = oRow[0].ToString();
                        if (!lstUniqueValues.Contains(strValue))
                            lstUniqueValues.Add(strValue);
                    }
                }
                
                // Insert into Value dropdown
                foreach (string strValue in lstUniqueValues)
                {
                    ValueDropdown.Items.Add(strValue);
                }

                // Select first item
                if (ValueDropdown.Items.Count > 0)
                    ValueDropdown.SelectedIndex = 0;
            }
            catch (Exception err)
            {
                MessageBox.Show("There was a problem determining the possible filter value options.\n" + err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                OKButton.Enabled = false;
            }
        }

        /// <summary>
        /// Event handler for OK button, sets dialog properties and closes dialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OKButton_Click(object sender, EventArgs e)
        {
            if ((ColumnDropdown.SelectedItem.ToString().Length == 0) || (ValueDropdown.SelectedItem.ToString().Length == 0))
            {
                FilterColumn = "";
                FilterValue = "";
            }
            else
            {
                FilterColumn = ColumnDropdown.SelectedItem.ToString();
                FilterValue = ValueDropdown.SelectedItem.ToString();
            }
            this.Close();
        }

        /// <summary>
        /// Event handler for Cancel button, closes dialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion // Event handlers
    }
}
